package com.ly.ocw.service;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.ly.ocw.comm.Delete;
import com.ly.ocw.comm.Error;
import com.ly.ocw.comm.MyPage;
import com.ly.ocw.entity.CrmMember;
import com.ly.ocw.exception.ServerException;
import com.ly.ocw.repository.CrmMemberDao;
import com.ly.ocw.service.weixin.WeixinCardService;
import com.ly.ocw.soap.CrmHttpUtils;
import com.ly.ocw.soap.memrec.DTMemberRecordSearchResp.Member;
import com.ly.ocw.soap.telvalid.DTTelephoneValidityResp;
import com.ly.ocw.soap.telvalid.DTTelephoneValidityResp.Return;

/**
 * 
 * 
 * @author Peter
 */
// Spring Service Bean的标识.
@Component
public class CrmMemberService {
	
	private static DecimalFormat df = new DecimalFormat("0000.##");
	
	// CRM 接口URL
	//IF-CRM-030 查询手机号码email昵称是否已存在
	@Value("${CRM.IF-CRM-030.SI_TelephoneValidity_os.URL}")
	private String SI_TelephoneValidity_os_URL;
	
	//IF-CRM-053 会员等级信息查询
	@Value("${CRM.IF-CRM-053.SI_MemberGradeSearch_os.URL}")
	private String SI_MemberGradeSearch_os_URL;
	
	//IF-CRM-007 会员全记录查询
	@Value("${CRM.IF-CRM-007.SI_MemberRecordSearch_os.URL}")
	private String SI_MemberRecordSearch_os_URL;
	

	private static Logger logger = LoggerFactory.getLogger(CrmMemberService.class);

	@Autowired
	private CrmMemberDao crmMemberDao;

	@Autowired
	private WeixinCardService weixinCardService;

	public CrmMember getById(Long id) {
		return crmMemberDao.getById(id);
	}

	public List<CrmMember> getAll() {
		return crmMemberDao.getAll();
	}

	/**
	 * 分页查询
	 * 
	 * @param overtime
	 * @param pageStart
	 * @param pageSize
	 * @return
	 */
	public MyPage<CrmMember> searchPage(CrmMember crmMember, int currentPage, int pageSize) {
		MyPage<CrmMember> myPage = new MyPage<CrmMember>();

		Long count = crmMemberDao.searchCount(crmMember);

		int pageStart = (currentPage - 1) < 0 ? 0 : (currentPage - 1) * pageSize;
		List<CrmMember> list = crmMemberDao.searchPage(crmMember, pageStart, pageSize);

		myPage.setCount(count);
		myPage.setContent(list);

		return myPage;
	}

	public void save(CrmMember crmMember) {
		crmMemberDao.save(crmMember);
	}

	public void update(CrmMember crmMember) {
		crmMemberDao.update(crmMember);
	}

	/**
	 * 软删除
	 */
	public void delete(Long id) {
		crmMemberDao.delete(id);
	}

	// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	// //根据手机号从CRM查询会员信息
	public CrmMember receiveMemberInfo(String cardId, String mobilePhone) throws ClientProtocolException, IOException {
		
		CrmMember oldCcrmMember = crmMemberDao.getByCardIdAndMobile(cardId,mobilePhone);
		
		// 调CRM 验证会员是否存在(会员id、会员昵称、会员状态 100020 此会员正常)
		CrmMember crmMember = telephoneValidity(mobilePhone);
		crmMember.setCardid(cardId);// 将cardId更新到数据库
		crmMember.setMobile(mobilePhone);

		// 调CRM 查询会员等级信息(会员外卡号、会员等级、到期日期、当前经验值、当前等级保级所需经验值、当前等级升级所需经验值)
		memberGradeSearch(crmMember);

		// 调CRM 查询会员详细信息(会员等级、会员积分余额)
		memberRecordSearch(crmMember);

		crmMember.setCreateDate(new Date());
		crmMember.setUpdateDate(new Date());
		crmMember.setDeleted(Delete.Enabled.longValue());
		
		
		//已有会员卡，更新
		if(oldCcrmMember != null){
			crmMember.setId(oldCcrmMember.getId());
			crmMemberDao.update(crmMember);
		}else{
			crmMemberDao.save(crmMember);
		}

		return crmMember;
	}

	// 调CRM 查询会员详细信息
	private void memberRecordSearch(CrmMember crmMember) throws ClientProtocolException, IOException {

		// 设置入参数

		List<Member> memberList;
		try {
			com.ly.ocw.soap.memrec.DTMemberRecordSearchResp _siMemberRecordSearchOs__return = CrmHttpUtils.memberRecordSearchReq(SI_MemberRecordSearch_os_URL,crmMember.getMemid()).getBody().getDTMemberRecordSearchResp();
			logger.info("siMemberRecordSearchOs.result=" + _siMemberRecordSearchOs__return);
			memberList = _siMemberRecordSearchOs__return.getMember();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new ServerException(Error._50000, Error._50000_MSG);
		}

		Member member = null;
		if (memberList == null || memberList.size() == 0) {
			throw new ServerException(Error._50001, Error._50001_MSG);
		} else {
			member = memberList.get(0);
			if ("100026".equals(member.getRETURNCODE())) {
				throw new ServerException("crm_code_100026", "无有效会员卡");
			}
		}
		logger.info("_siMemberRecordSearchOs_mtMemberRecordSearchReq.Member " + member);
		crmMember.setTierLevel(member.getTIERLEVEL());// 会员等级
		crmMember.setPointsBalance(member.getPTBALANCE());// 积分余额

	}

	// 调CRM 查询会员等级信息
	private void memberGradeSearch(CrmMember crmMember) throws ClientProtocolException, IOException {

		List<com.ly.ocw.soap.memgra.DTMemberGradeSearchResp.Row> responseRows;
		try {
			com.ly.ocw.soap.memgra.DTMemberGradeSearchResp _siMemberGradeSearchOs__return = CrmHttpUtils.memberGradeSearchReq(SI_MemberGradeSearch_os_URL,crmMember.getMemid()).getBody().getDTMemberGradeSearchResp();
			logger.info("siMemberGradeSearchOs.result=" + _siMemberGradeSearchOs__return);
			responseRows = _siMemberGradeSearchOs__return.getRow();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new ServerException(Error._50000, Error._50000_MSG);
		}

		com.ly.ocw.soap.memgra.DTMemberGradeSearchResp.Row respRow = null;
		if (responseRows == null || responseRows.size() == 0) {
			throw new ServerException(Error._50001, Error._50001_MSG);
		} else {
			respRow = responseRows.get(0);
			if ("100026".equals(respRow.getRETURNCODE())) {
				throw new ServerException("crm_code_100026", "无有效会员卡");
			}
		}
		logger.info("com.ly.ocw.soap.memgra.DTMemberGradeSearchResp.Row " + respRow);
		crmMember.setCardNumber(respRow.getEXTERNALCARDNU());// 会员外卡号
		crmMember.setTierLevel(respRow.getTIERLEVEL());// 会员等级
		crmMember.setDateto(respRow.getDATETO());// 到期日期
		crmMember.setPresentExperiencePoints(respRow.getPRESENTEXPERIENCEPOINTS());// 当前经验值
		crmMember.setRelegationExperiencePoints(respRow.getRELEGATIONEXPERIENCEPOINTSNEED());// 当前等级保级所需经验值
		crmMember.setPromoteExperiencePointsNeed(respRow.getPROMOTEEXPERIENCEPOINTSNEED());// 当前等级升级所需经验值

	}

	// 调CRM 验证会员是否存在
	public CrmMember telephoneValidity(String mobilePhone){


		List<DTTelephoneValidityResp.Return> returnList = null;
		try {
			logger.info("Invoking siTelephoneValidityOs...");

			com.ly.ocw.soap.telvalid.DTTelephoneValidityResp _siTelephoneValidityOs__return = CrmHttpUtils.telephoneValidityReq(SI_TelephoneValidity_os_URL,mobilePhone).getBody().getDTTelephoneValidityResp();
			logger.info("siTelephoneValidityOs.result=" + _siTelephoneValidityOs__return);

			returnList = _siTelephoneValidityOs__return.getReturn();
		} catch (ClientProtocolException e) {
			logger.error(e.getMessage(),e);
			throw new ServerException(Error._50000, Error._50000_MSG);
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
			throw new ServerException(Error._50000, Error._50000_MSG);
		}

		Return r = null;
		if (returnList == null || returnList.size() == 0) {
			throw new ServerException(Error._50001, Error._50001_MSG);
		} else {
			r = returnList.get(0);
			if ("100001".equals(r.getRETURNCODE())) {
				throw new ServerException("crm_code_100001", "此手机号会员不存在");
			}
		}

		CrmMember crmMenber = new CrmMember();

		crmMenber.setMemid(r.getLOYMEMID());// 会员id
		crmMenber.setNickame(r.getNAMENICK());// 会员昵称
		crmMenber.setStatus(r.getMSHSTATUS());// 会员状态 100020 此会员正常；100002
												// 此会员已否决；100003 此会员已过期；100004
												// 此会员已暂停
		logger.info("siTelephoneValidityOs.result " + r);
		return crmMenber;
	}

	public CrmMember getByCardIdAndCodeAndOpenid(String cardId, String code, String openid) {
		return crmMemberDao.getByCardIdAndCodeAndOpenid(cardId, code, openid);
	}

	/**
	 * 
	 * @param cardId
	 * @param openid
	 * @return
	 */
	public CrmMember getByCardIdAndOpenid(String cardId, String openid) {
		return crmMemberDao.getByCardIdAndOpenid(cardId, openid);
	}

	public CrmMember getByCardIdAndCode(String cardId, String code ) {
		// TODO Auto-generated method stub
		return crmMemberDao.getByCardIdAndCode(cardId, code);
	}

	/**
	 * 更新会员积分信息
	 * 
	 * 1. 调用crm读取最新会员信息 2. 更新数据库 3. 调用微信接口，更新会员积分
	 * 
	 * @param cardId
	 * @param code
	 *            会员卡号
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public void updateCrmMemberInfo(String cardId, String code, String openid) throws ClientProtocolException, IOException {
		logger.info("更新会员积分信息-->>：{" + cardId + ",code：" + code + ",openid:" + openid + "}");
		CrmMember crmMember = crmMemberDao.getByCardIdAndCode(cardId, code);
		if (crmMember == null) {
			logger.error("会员不存在 null");
		} else {
			String oldbonus = crmMember.getPointsBalance();// 积分余额

			if (StringUtils.isBlank(crmMember.getOpenid())) {
				crmMember.setOpenid(openid);
			}

			// 调CRM 查询会员详细信息(会员积分余额、会员等级)
			memberRecordSearch(crmMember);

			// 2. 更新数据库
			crmMemberDao.update(crmMember);

			Double add_bonus = Double.valueOf(crmMember.getPointsBalance()) - Double.valueOf(oldbonus);
			
			if(add_bonus.intValue() != 0){
				// 3. 调用微信接口，更新会员积分
				weixinCardService.updateWeixinMembercard(crmMember, add_bonus);
			}
		}
	}
	
	/**
	 * 更新会员积分信息
	 * 
	 *  2. 更新数据库 3. 调用微信接口，更新会员积分
	 * 
	 * @param cardId
	 * @param code
	 *            会员卡号
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public void updateDemoMemberInfo(String cardId, String code, String openid) throws ClientProtocolException, IOException {
		logger.info("更新会员积分信息-->>：{" + cardId + ",code：" + code + ",openid:" + openid + "}");
		CrmMember crmMember = crmMemberDao.getByCardIdAndCode(cardId, code);
		if (crmMember == null) {
			logger.error("会员不存在 null");
		} else {
			String oldbonus = crmMember.getPointsBalance();// 积分余额

			if (StringUtils.isBlank(crmMember.getOpenid())) {
				crmMember.setOpenid(openid);
			}

			// 2. 更新数据库
			crmMemberDao.update(crmMember);

			Double add_bonus = Double.valueOf(crmMember.getPointsBalance()) - Double.valueOf(oldbonus);
			
			if(add_bonus.intValue() != 0){
				// 3. 调用微信接口，更新会员积分
				weixinCardService.updateWeixinMembercard(crmMember, add_bonus);
			}
		}
	}

	public CrmMember receiveRandomMemberInfo(String cardId, String mobilePhone) {
		CrmMember member =new CrmMember();
		member.setCardid(cardId);
		member.setCardNumber(genCode());
		member.setCreateDate(new Date());
		member.setDeleted(Delete.Enabled.longValue());
		member.setMobile(mobilePhone);
		member.setPointsBalance(RandomUtils.nextLong(2000L, 5000L)+"");
		member.setPresentExperiencePoints(RandomUtils.nextLong(2000L, 5000L)+"");
		member.setRelegationExperiencePoints(RandomUtils.nextLong(2000L, 5000L)+"");
		member.setTierLevel(randomLevel());
		member.setUpdateDate(new Date());
		
		crmMemberDao.save(member);
		return member;
	}
	
	/**
	 * 生成随机code 0000111122223333
	 * 
	 * @return
	 */
	private String genCode() {
		String code = "";
		Random r = new Random();
		code = df.format(r.nextInt(1000)) + "" + df.format(r.nextInt(1000)) + "" + df.format(r.nextInt(1000)) + "" + df.format(r.nextInt(1000));

		return code;
	}
	
	private static String randomLevel(){
		String []  levels = {"ZA","ZB","ZC"};
		Random r = new Random();
		
		return levels[r.nextInt(3)];
		
	}
	
	public static void main(String[] args) {
		for (int i = 0; i < 20; i++) {
			System.out.println(CrmMemberService.randomLevel());
		}
	}

}
